"""用户模型"""
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from sqlalchemy import Column, Integer, String, Boolean, DateTime, Text
from sqlalchemy.ext.hybrid import hybrid_property

from app.extensions import db


class User(db.Model):
    """用户模型"""
    
    __tablename__ = 'users'
    
    id = Column(Integer, primary_key=True, comment='用户ID')
    username = Column(String(80), unique=True, nullable=False, comment='用户名')
    email = Column(String(120), unique=True, nullable=False, comment='邮箱')
    _password_hash = Column('password_hash', String(256), nullable=False, comment='密码哈希')
    first_name = Column(String(50), comment='名')
    last_name = Column(String(50), comment='姓')
    avatar_url = Column(Text, comment='头像URL')
    is_active = Column(Boolean, default=True, comment='是否激活')
    is_admin = Column(Boolean, default=False, comment='是否管理员')
    created_at = Column(DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')
    last_login_at = Column(DateTime, comment='最后登录时间')
    
    @hybrid_property
    def password(self):
        """密码属性"""
        raise AttributeError('密码不能直接读取')
    
    @password.setter
    def password(self, password: str):
        """设置密码"""
        self._password_hash = generate_password_hash(password)
    
    def check_password(self, password: str) -> bool:
        """验证密码"""
        return check_password_hash(self._password_hash, password)
    
    @property
    def full_name(self) -> str:
        """获取全名"""
        if self.first_name and self.last_name:
            return f"{self.last_name} {self.first_name}"
        return self.username
    
    def to_dict(self, include_sensitive: bool = False) -> dict:
        """转换为字典"""
        data = {
            'id': self.id,
            'username': self.username,
            'email': self.email,
            'first_name': self.first_name,
            'last_name': self.last_name,
            'full_name': self.full_name,
            'avatar_url': self.avatar_url,
            'is_active': self.is_active,
            'is_admin': self.is_admin,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None,
            'last_login_at': self.last_login_at.isoformat() if self.last_login_at else None,
        }
        
        return data
    
    def update_last_login(self):
        """更新最后登录时间"""
        self.last_login_at = datetime.utcnow()
        db.session.commit()
    
    def __repr__(self):
        return f'<User {self.username}>'
    
    def __str__(self):
        return self.username 